import { ref, reactive } from 'vue'
import store from '@/app/store'
import { get, update, status, outbound, copy } from '@/api/store/order'

// 初始化
const orderStore = store()

// 发票类型
orderStore.data = ref({
  ticket: 'ticket'
})

// 分页
orderStore.page = reactive({
  current: 1,
  pageSize: 0,
  total: 0,
  pageSizeOptions: [10, 20, 50, 100],
  loading: false
})

// 查询类型
orderStore.where = reactive({ 
  key: 'code', 
  value: '',
  time: []
})

// 生成查询数据
orderStore.getWhere = () => {
  // 查询方式
  const where = { 
    [orderStore.where.key]: orderStore.where.value, 
    time: orderStore.where.time
  }
  // 合并数据
  return Object.assign(where, orderStore.getData())
}

orderStore.get = () => {
  return new Promise((resolve, jeject) => {
    orderStore.page.loading = true
    get(orderStore.getWhere()).then(res => {
      orderStore.setList(res.data)
      // 分页
      orderStore.page.current = res.current_page
      orderStore.page.pageSize = res.per_page
      orderStore.page.total = res.total
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      orderStore.page.loading = false
    })
  })
}

orderStore.update = (...arge) => {
  return new Promise((resolve, jeject) => {
    update(...arge).then(res => {
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

orderStore.status = (...arge) => {
  return new Promise((resolve, jeject) => {
    status(...arge).then(res => {
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

orderStore.del = (...arge) => {
  return new Promise((resolve, jeject) => {
    del(...arge).then(res => {
      orderStore.get()
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 入库
orderStore.outbound = id => {
  return new Promise((resolve, jeject) => {
    outbound(id).then(res => {
      orderStore.reset(1)
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 重置请求
orderStore.reset = (page, size) => {
  orderStore.page.current = page
  orderStore.page.pageSize = size
  orderStore.getData().page = page
  orderStore.getData().page_size = size

  // 开始加载
  orderStore.get()
}

// 转发票
orderStore.copy = (data) => {
  return new Promise((resolve, jeject) => {
    copy(data).then(res => {
      orderStore.get()
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

export default orderStore